//
//  BYGameBoxView.m
//  Embedded-WebServer
//
//  Created by Ampaw on 2019/2/26.
//  Copyright © 2019年 Ampaw. All rights reserved.
//

#import "BYGameBoxView.h"
#import "BYMasonry.h"

#import "GCDWebServer.h"
#import "GCDWebServerDataResponse.h"


#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height

@interface BYGameBoxView ()<UIWebViewDelegate>{
    GCDWebServer* _webServer;
}
@property (nonatomic,strong) UIWebView *XgameView;
@property (nonatomic,strong) UIImageView *qidongtuImgView;
@property (nonatomic,assign) UIInterfaceOrientationMask orientation;

@end

@implementation BYGameBoxView

- (instancetype)initWithOrientation:(UIInterfaceOrientationMask)orientation {
    self = [super init];
    if (self) {
        self.orientation = orientation;
        [self buildGame];
    }
    return self;
}

- (void)buildGame {
    _webServer = [[GCDWebServer alloc] init];
    NSString* websitePath = [[NSBundle mainBundle] pathForResource:@"www" ofType:nil];
    [_webServer addGETHandlerForBasePath:@"/" directoryPath:websitePath indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
    [_webServer addHandlerForMethod:@"GET"
                          pathRegex:@"/.*\\.html"
                       requestClass:[GCDWebServerRequest class]
                       processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
                           NSDictionary* variables = [NSDictionary dictionaryWithObjectsAndKeys:@"value", @"variable", nil];
                           return [GCDWebServerDataResponse responseWithHTMLTemplate:[websitePath stringByAppendingPathComponent:request.path] variables:variables];
                       }
     ];
    [_webServer addHandlerForMethod:@"GET"
                               path:@"/"
                       requestClass:[GCDWebServerRequest class]
                       processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
                           return [GCDWebServerResponse responseWithRedirect:[NSURL URLWithString:@"index.html" relativeToURL:request.URL] permanent:NO];
                       }
     ];
    [_webServer startWithPort:8090 bonjourName:nil];
    
    
    [self addSubview:self.XgameView];
    [self.XgameView mas_makeConstraints:^(BYMASConstraintMaker *make) {
        if (self.orientation == UIInterfaceOrientationMaskPortrait) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }else if([self isLandscape]){
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }else {
            make.centerY.equalTo(self.mas_centerY);
            make.centerX.equalTo(self.mas_centerX);
            make.size.mas_equalTo(CGSizeMake(SCREEN_HEIGHT, SCREEN_WIDTH));
        }
    }];
    [self addSubview:self.qidongtuImgView];
    [self.qidongtuImgView mas_makeConstraints:^(BYMASConstraintMaker *make) {
        if (self.orientation == UIInterfaceOrientationMaskPortrait) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }else if([self isLandscape]){
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }else {
            make.centerY.equalTo(self.mas_centerY);
            make.centerX.equalTo(self.mas_centerX);
            make.size.mas_equalTo(CGSizeMake(SCREEN_HEIGHT, SCREEN_WIDTH));
        }
    }];
    [self qidongXGame];
}

-(void)qidongXGame {
    self.XgameView.scrollView.bounces=NO;
    self.XgameView.scrollView.scrollEnabled=NO;
    self.XgameView.delegate=self;
    NSString *gameURL = @"http://127.0.0.1:8090";
    NSURL *url =[NSURL URLWithString:gameURL];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [self.XgameView loadRequest:request];
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *ojp1 = @"docum#ent.docu#me#nt#Ele#ment.st#yle.webk#itUs#erSe#lect='none';";
    ojp1 = [ojp1 stringByReplacingOccurrencesOfString:@"#" withString:@""];
    NSString *ojp2 = @"docu#ment.do#cum#entEle#ment.st#yle.webki#tTouch#Cal#lout='none';";
    ojp2 = [ojp2 stringByReplacingOccurrencesOfString:@"#" withString:@""];
    [webView stringByEvaluatingJavaScriptFromString:ojp1];
    [webView stringByEvaluatingJavaScriptFromString:ojp2];
    [self removeqidongView];
}

#pragma mark - Other
- (BOOL)isLandscape {
    CGFloat width = CGRectGetWidth(self.bounds);
    CGFloat height = CGRectGetHeight(self.bounds);
    if (width > height) {
        return YES;
    }
    return NO;
}

#pragma mark - Action
- (void)addqidongView {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:self.qidongtuImgView];
    });
}
- (void)removeqidongView {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.qidongtuImgView removeFromSuperview];
    });
}

#pragma mark - setter & getter
-(UIWebView *)XgameView {
    if (!_XgameView) {
        CGRect frame = CGRectZero;
        _XgameView=[[UIWebView alloc] initWithFrame:frame];
        if (self.orientation != UIInterfaceOrientationMaskPortrait && ![self isLandscape]) {
            _XgameView.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(270));
        }
    }
    return _XgameView;
}
- (UIImageView *)qidongtuImgView {
    if (!_qidongtuImgView) {
        _qidongtuImgView = [[UIImageView alloc] init];
        _qidongtuImgView.backgroundColor=[UIColor blackColor];
        _qidongtuImgView.image = [UIImage imageNamed:@"loading"];
        if (self.orientation != UIInterfaceOrientationMaskPortrait && ![self isLandscape]) {
            _qidongtuImgView.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(270));
        }
    }
    return _qidongtuImgView;
}

@end
